package com.chenyao.bookstore.dataprovider.impl;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

import com.chenyao.bookstore.util.Constants;

/**
 * The database connection factory class.
 * 
 * @author YongXia.
 * 
 * @since jdk1.6
 * @version 1.0
 * 
 */
public final class ConnectionFactory {

	private static String DRIVER;
	private static String PASSWORD;
	private static String URL;
	private static String USERNAME;

	/**
	 * load the database connection properties file. initialize the connection
	 * parameters.
	 */
	static {
		Properties prop = null;
		InputStream is = null;
		try {
			prop = new Properties();
			is = ConnectionFactory.class.getClassLoader().getResourceAsStream(Constants.DB_CONN_PATH);
			prop.load(is);
			ConnectionFactory.DRIVER = prop.getProperty(Constants.DB_CONN_DRIVER);
			ConnectionFactory.URL = prop.getProperty(Constants.DB_CONN_URL);
			ConnectionFactory.USERNAME = prop.getProperty(Constants.DB_CONN_USERNAME);
			ConnectionFactory.PASSWORD = prop.getProperty(Constants.DB_CONN_PASSWORD);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (null != is)
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
	}

	/**
	 * Get a database connection instance.
	 * 
	 * @author YongXia.
	 * 
	 * @since jdk1.6
	 * @version 1.0
	 * 
	 * @return A database connection instance.
	 * @throws SQLException
	 * @throws ClassNotFoundException
	 */
	public final static Connection getConnection() throws SQLException, ClassNotFoundException {
		Class.forName(ConnectionFactory.DRIVER);
		return DriverManager.getConnection(ConnectionFactory.URL, ConnectionFactory.USERNAME,
				ConnectionFactory.PASSWORD);
	}

	private ConnectionFactory() {
	}

}
